package com.gitee.dufafei.spark.deploy

import java.util.concurrent.CountDownLatch

import org.apache.spark.launcher.SparkAppHandle.State
import org.apache.spark.launcher.{SparkAppHandle, SparkLauncher}

class Launcher {

  var sparkAppHandle: SparkAppHandle = _

  def submit(): Unit = {
    val countDownLatch = new CountDownLatch(1)
    sparkAppHandle = new SparkLauncher()
      .setJavaHome("")
      .setSparkHome("")
      .setAppName("")
      .setMaster("yarn")
      .setDeployMode("cluster")
      .setMainClass("")
      .setAppResource("")
      //.setConf("spark.driver.memory", "2g")
      //.setConf("spark.executor.cores", "3")
      //.setConf("spark.executor.memory", "1g")
      .addAppArgs() // 自定义参数
      .setVerbose(true) // 是否为SparkSubmit启用详细报告
      .startApplication(new SparkAppHandle.Listener{

        override def stateChanged(handle: SparkAppHandle): Unit = {
          val state = handle.getState
          println(state)
          if (state.equals(State.SUBMITTED)) println(handle.getAppId)
          if (state.isFinal) countDownLatch.countDown()
        }

        override def infoChanged(handle: SparkAppHandle): Unit = {

        }
      })
    countDownLatch.await()
  }

  def cancel(): Unit = {
    if (sparkAppHandle != null) sparkAppHandle.stop()
  }
}
